function createBrowserHistory(){
  const globalHistory = window.history;
  let state; 
  let listeners = [];
  function go(n){
    globalHistory.go(n);
  };
  function goBack(){
    globalHistory.go(-1);
  };
  function goForward(){
    globalHistory.go(1)
  };
  function replace(){

  };

  // 以后当路径发生变化了可以通知listener
  // 1.用户手工输入新的路径 2.调用push replace go goback goForward
  function listen(listener){
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(item => item !== listener)
    }
  };
  
  function push(pathname, nextState){
    const action = "PUSH";
    if(typeof pathname === "object"){
      state = pathname.state;
      pathname = pathname.pathname;
    }else{
      state = nextState;
    }
    globalHistory.pushState(state, null, pathname);
    let location = {
      pathname,
      state,
    }
    notify({
      action,
      location
    })
  };
  function notify({action,location }){
    history.action= action;
    history.location = location;
    history.length = globalHistory.length;
    // 通知所有的监听函数执行
    listeners.forEach(listener => {
      listener({
        action,
        location,
      })
    })
  };
  window.addEventListener("popstate", () => {
    let location = {
      state: globalHistory.state, // 状态是从windowHistory上取值
      pathname: window.location.pathname // 路径是从location上取值pathname
    };
    notify({
      action: "POP",
      location
    });
  });
  
  // 初始化历史对象
  const history = {
    action: 'POP',
    go,
    goBack,
    goForward,
    push,
    replace,
    listen,
    location: {
      pathname: window.location.pathname, // 路径名
      state: globalHistory.state // 路径对应的状态值
    }
  }
  return history;
}

export default createBrowserHistory;
